package com.af.community.smart.business

import android.content.Intent
import android.os.Bundle
import android.view.View
import com.af.community.smart.base.*
import com.af.community.smart.model.CommonData
import com.af.community.smart.utils.*
import com.af.community.smart.utils.DialogHelper.showItemDialog
import com.af.community.smart.view.FullyGridLayoutManager
import com.af.community.smart.viewmodel.ReportViewModel
import com.lxj.matisse.Matisse
import com.lxj.matisse.MimeType
import com.sunfusheng.GlideImageView
import kotlinx.android.synthetic.main.activity_report.*
import net.idik.lib.slimadapter.SlimAdapter
import org.jetbrains.anko.toast
import org.koin.androidx.viewmodel.ext.android.getViewModel

class ReportActivity : BaseActivity() {

    private val REQUEST_CODE_CHOOSE = 32
    private val list = ArrayList<String>()
    private val eventList = ArrayList<CommonData>()
    private var mTypeValue = ""
    private var mTypeTitle = ""
    private var mTypeDetail = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_report)
        initTitle(title = "网格事件上报")

        mAdapter.updateData(list.apply { add("") })
    }

    override fun getViewModel() = getViewModel<ReportViewModel>()

    override fun initTitle(title: String, name: String) {
        super.initTitle(title, name)
        report_imgs.apply {
            isNestedScrollingEnabled = false
            layoutManager = FullyGridLayoutManager(baseContext, 3)
        }

        mAdapter = SlimAdapter.create()
            .register<String>(R.layout.item_report_img) { data, injector ->

                val index = list.indexOf(data)

                injector.visibility(
                    R.id.item_report_del,
                    if (data.isEmpty()) View.INVISIBLE else View.VISIBLE
                )
                    .with<GlideImageView>(R.id.item_report) {
                    if (data.isEmpty()) it.loadDrawable(R.mipmap.icon_upload)
                    else it.loadRoundedImage(data.scaleImage())
                }
                    .clicked(R.id.item_report) {
                        if (data.isEmpty()) {
                            val selectSize = list.filter { it.isNotEmpty() }.size
                            mPosition = -1

                            Matisse.from(baseContext)
                                .choose(MimeType.ofImage())
                                .theme(R.style.Matisse_Blue)
                                .capture(true)
                                .originalEnable(false)
                                .maxSelectable(5 - selectSize)
                                .forResult(REQUEST_CODE_CHOOSE)
                        } else {
                            mPosition = index
                            Matisse.from(baseContext)
                                .choose(MimeType.ofImage())
                                .theme(R.style.Matisse_Blue)
                                .capture(true)
                                .originalEnable(false)
                                .maxSelectable(1)
                                .forResult(REQUEST_CODE_CHOOSE)
                        }
                    }
                    .clicked(R.id.item_report_del) {
                        list.remove(data)
                        mAdapter.notifyItemRemoved(index)
                        // 受到影响的item都需要刷新position
                        mAdapter.notifyItemRangeChanged(index, list.size - index)
                        if ("" !in list) {
                            list.add("")
                            mAdapter.notifyItemInserted(list.size - 1)
                        }
                    }
            }
            .attachTo(report_imgs)

        report_type.oneClick {
            if (eventList.isEmpty()) {
                getViewModel().getEventType()
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeByFinally(
                        event = getViewModel(),
                        onSuccess = { data ->
                            eventList.addItems(data)
                            if (eventList.isNotEmpty()) {
                                val items = ArrayList<String>()
                                eventList.mapTo(items) { it.dictLabel }
                                showItemDialog(
                                    "请选择事件类型",
                                    items.indexOf(mTypeTitle),
                                    items
                                ) { index, hint ->
                                    mTypeValue = eventList[index].dictValue
                                    mTypeTitle = hint
                                    mTypeDetail = ""
                                    report_type.setRightString(hint)
                                    report_matter.setRightString("")
                                }
                            }
                        }
                    )
            } else {
                val items = ArrayList<String>()
                eventList.mapTo(items) { it.dictLabel }
                showItemDialog(
                    "请选择事件类型",
                    items.indexOf(mTypeTitle),
                    items
                ) { index, hint ->
                    mTypeValue = eventList[index].dictValue
                    mTypeTitle = hint
                    mTypeDetail = ""
                    report_type.setRightString(hint)
                    report_matter.setRightString("")
                }
            }
        }
        report_matter.oneClick {
            if (mTypeValue.isEmpty()) {
                toast("请先选择事件类型")
                return@oneClick
            }

            getViewModel().getSecondType(mTypeValue)
                .bindLifeCycle(getLifecycleOwner())
                .subscribeByFinally(
                    event = getViewModel(),
                    onSuccess = { data ->
                        if (data.isNullOrEmpty()) {
                            toast("暂无相关具体事项！")
                        } else {
                            val items = ArrayList<String>()
                            data.mapTo(items) { it.dictLabel }

                            showItemDialog(
                                "请选择具体事项",
                                items.indexOf(mTypeDetail),
                                items
                            ) { _, hint ->
                                mTypeDetail = hint
                                report_matter.setRightString(hint)
                            }
                        }
                    }
                )
        }
    }

    override fun doClick(v: View) {
        super.doClick(v)
        when (v.id) {
            R.id.bt_report -> {
                when {
                    mTypeTitle.isEmpty() -> {
                        toast("请选择事件类型")
                        return
                    }
                    mTypeDetail.isEmpty() -> {
                        toast("请选择具体事项")
                        return
                    }
                    report_memo.text.isBlank() -> {
                        toast("请输入描述内容")
                        return
                    }
                    list.none { it.isNotEmpty() } -> {
                        toast("请选择上传图片")
                        return
                    }
                }

                getViewModel().getReportData(
                    "userId" to getString("userId"),
                    "eventType" to mTypeTitle,
                    "eventTitle" to mTypeDetail,
                    "eventDetail" to report_memo.trimString(),
                    "remark" to list.filter { it.isNotEmpty() }.joinToString(",")
                )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeByNoError(
                        event = getViewModel(),
                        onSuccess = {
                            toast("事件上报提交成功！")
                            ActivityStack.screenManager.popActivities(this@ReportActivity::class.java)
                        }
                    )
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            val imgSelect = ArrayList<String>()
            val imgList = Matisse.obtainSelectPathResult(data)
            val imgCapture = Matisse.obtainCaptureImageResult(data)

            when {
                !imgList.isNullOrEmpty() -> imgSelect.addAll(imgList)
                imgCapture != null -> imgSelect.add(imgCapture)
            }

            if (imgSelect.isNotEmpty()) {
                OSSHelper.manager.uploadImages(
                    pathList = imgSelect,
                    onBefore = { showLoading() },
                    onAfter = { dismissLoading() },
                    onSuccess = { _, result ->
                        if (result != null) {
                            val img = result.responseHeader["url"].orEmpty()
                            if (img.isNotEmpty()) {
                                if (mPosition < 0) {
                                    list.remove("")
                                    list.add(img)
                                    if (list.size < 5) list.add("")
                                } else {
                                    list.removeAt(mPosition)
                                    list.add(mPosition, img)
                                }
                                mAdapter.notifyDataSetChanged()
                            }
                        }
                    },
                    OnError = { index, _ -> if (index < 0) toast("网络异常，请稍候再试！") }
                )
            }
        }
    }

}
